package com.oly.cms.hand.controller.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.Producer;
import com.grace.common.config.GraceConfig;
import com.grace.common.constant.CacheConstants;
import com.grace.common.constant.Constants;
import com.grace.common.core.domain.AjaxResult;
import com.grace.common.core.domain.entity.SysUser;
import com.grace.common.enums.SysConfigGroups;
import com.grace.common.utils.FormatUtil;
import com.grace.common.utils.sign.Base64;
import com.grace.common.utils.uuid.IdUtils;
import com.grace.mail.domain.MailUsedEnums;
import com.grace.mail.domain.OlyMail;
import com.grace.mail.service.impl.OlyMailServiceImpl;
import com.grace.redis.utils.RedisCache;
import com.grace.system.service.impl.SysSearchConfigServiceImpl;
import com.grace.system.service.impl.SysUserServiceImpl;

/**
 * 验证码操作处理
 * 
 * @author grace
 */
@RestController
public class CodeController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysSearchConfigServiceImpl configService;

    @Autowired
    private SysUserServiceImpl userServiceImpl;

    @Autowired
    private OlyMailServiceImpl mailServiceImpl;

    /**
     * 生成验证码
     */
    @GetMapping("/{themeName}/code/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled(SysConfigGroups.SYS_CONFIG.getValue());
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = GraceConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }
    
    /**
     * 邮件验证码
     * @param email
     * @return
     */
    @GetMapping("/{themeName}/code/getMailCode/{email}")
    public AjaxResult getMailCode(@PathVariable("email") String email) {
        // 验证是否为邮箱
        if (!FormatUtil.isEmail(email)) {
            return AjaxResult.error("邮箱错误");
        } else {
            // 保存验证码信息
            String uuid = IdUtils.simpleUUID();
            String verifyKey = CacheConstants.THIRD_CODE_KEY + uuid + "_" + email;
            SysUser sysUser = new SysUser();
            sysUser.setEmail(email);
            // 验证邮箱是否存在
            if (userServiceImpl.checkEmailUnique(sysUser)) {
                String code = String.valueOf(new Random().nextInt(999999));
                redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
                OlyMail olyMail = new OlyMail();
                olyMail.setToMail(email);
                olyMail.setSubject("你收到来止戈系统的注册账号的邮箱验证码");
                olyMail.setContent("你的验证码为：" + code + ",验证码有效时间为60秒,请及时验证!");
                olyMail.setMailUsed(MailUsedEnums.CODE.ordinal());
                mailServiceImpl.sendTextMail(olyMail, true);
                return AjaxResult.success("验证码发送成功！").put("thirdUuid", uuid);
            } else {
                return AjaxResult.error("邮箱已经注册！");
            }
        }
    }
}
